<template>
	<view class="wrapper perfect">
		<!--表单-->
		<view class="form" v-if="info?.reviewFlag == 1 && info?.examineFlag == 1">
			<uni-forms
				ref="formRef"
				:label-width="86">
				<uni-forms-item label="真实姓名">
					<view class="form-text main-flex">{{info.name}}</view>
				</uni-forms-item>
				<uni-forms-item label="企业/门店">
					<view class="form-text main-flex">{{info.company}}</view>
				</uni-forms-item>
				<uni-forms-item label="城市">
					<view class="form-text main-flex">{{info.province}}</view>
				</uni-forms-item>
				<uni-forms-item label="详细地址">
					<view class="form-text main-flex">{{info.addr}}</view>
				</uni-forms-item>
				<uni-forms-item label="门店照片">
					<view class="form-text">
						<image class="form-text-img" @click="previewImg(info.storeImg)" mode="aspectFill" :src="imgUrl(info.storeImg)"></image>
					</view>
				</uni-forms-item>
				<uni-forms-item label="门店环境">
					<view class="form-text">
						<image class="form-text-img" @click="previewImg(info.storeFaceImg)" mode="aspectFill" :src="imgUrl(info.storeFaceImg)"></image>
					</view>
				</uni-forms-item>
				<uni-forms-item label="营业执照">
					<view class="form-text">
						<image class="form-text-img" @click="previewImg(info.businessLicenseImg)" mode="aspectFill" :src="imgUrl(info.businessLicenseImg)"></image>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="form" v-else>
			<uni-forms
				:modelValue="form"
				ref="formRef"
				:label-width="86"
				:rules="rules">
				<uni-forms-item label="真实姓名" name="name" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.name"
						placeholder="请输入真实姓名" />
				</uni-forms-item>
				<uni-forms-item label="企业/门店" name="company" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.company"
						placeholder="请输入企业/门店" />
				</uni-forms-item>
				<uni-forms-item label="城市" name="province" required>
					<uni-data-picker
						v-model="regionCode"
						placeholder="请选择城市"
						popup-title="请选择城市"
						:localdata="setStore.region"
						:border="false"
						:map="{text:'label',value:'value'}"
						@change="onChangeAddr">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="详细地址" name="addr" required>
					<uni-easyinput
						type="text"
						:inputBorder="false"
						primaryColor="#e3230e"
						v-model="form.addr"
						placeholder="街道、楼道号等" />
				</uni-forms-item>
				<uni-forms-item label="门店照片" name="storeImg" required>
					<u-upload
						:fileList="fileList.storeImg"
						@afterRead="afterRead"
						@delete="deletePic"
						name="storeImg"
						:maxCount="1"
						></u-upload>
					<uni-easyinput style="display: none;" v-model="form.storeImg" placeholder="上传门店照片" />
				</uni-forms-item>
				
				<uni-forms-item label="门店环境" name="storeFaceImg" required>
					<u-upload
						:fileList="fileList.storeFaceImg"
						@afterRead="afterRead"
						@delete="deletePic"
						name="storeFaceImg"
						:maxCount="1"
						></u-upload>
					<uni-easyinput style="display: none;" v-model="form.storeFaceImg" placeholder="上传门店环境" />
				</uni-forms-item>
				
				<uni-forms-item label="营业执照" name="businessLicenseImg" required>
					<u-upload
						:fileList="fileList.businessLicenseImg"
						@afterRead="afterRead"
						@delete="deletePic"
						name="businessLicenseImg"
						:maxCount="1"
						></u-upload>
					<uni-easyinput style="display: none;" v-model="form.businessLicenseImg" placeholder="上传营业执照" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<button v-if="!(info?.reviewFlag == 1 || info?.examineFlag == 1)" class="ty-button ty-button-confirm form-submit" :disabled="isSubmit" :loading="isSubmit" @click="submit">保存</button>
	</view>
</template>

<script setup>
import { computed, ref, watch, watchEffect } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { perfectInfo, perfectEdit } from "@/api/app_api/user"
import { upload } from "@/api/system/common"
import { throttle, debounce, test, sleep } from '@/uni_modules/uview-plus'
import modal from '@/plugins/modal'

	const userStore = useUserStore()
	const setStore = useSetStore()
	
	const type = ref('')
	onLoad((options) => {
		if (options.type) {
			type.value = options.type
		}
		getDetail()
	})
	
	// 获取详情
	const info = ref(null)
	const isLoading = ref(false)
	const isSave = ref(false)
	const getDetail = () => {
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		perfectInfo().then(res => {
			info.value = res.data
			isSave.value = res.data.reviewFlag == 1 && res.data.examineFlag == 1 ? false : true
			form.value = {
				name: res.data.name,
				company: res.data.company && res.data.company !== '待完善' ? res.data.company : '',
				province: res.data.province,
				addr: res.data.addr,
				businessLicenseImg: res.data.businessLicenseImg.indexOf('noimg.png') > -1 ? '' : res.data.businessLicenseImg,
				storeImg: res.data.storeImg.indexOf('noimg.png') > -1 ? '' : res.data.storeImg,
				storeFaceImg: res.data.storeFaceImg.indexOf('noimg.png') > -1 ? '' : res.data.storeFaceImg
			}
			fileList.value = {
				businessLicenseImg: imgUrlList(res.data, 'businessLicenseImg'),
				storeImg: imgUrlList(res.data, 'storeImg'),
				storeFaceImg: imgUrlList(res.data, 'storeFaceImg')
			}
			if (setStore.region.length > 0) {
				setRegionCode()
			}
			isLoading.value = false
			uni.hideLoading()
		}).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	const setRegionCode = () => {
		const firstFilter = setStore.region.filter(item => item.value == info.value.regionCode)
		const secondFilter = firstFilter?.[0]?.children.filter(item => info.value.province.indexOf(item.label) > -1) || []
		const thirdFilter = secondFilter?.[0]?.children.filter(item => info.value.province.indexOf(item.label) > -1) || []
		regionCode.value = thirdFilter?.[0].value || ''
	}
	
	watch(() => setStore.region, (nval, oval) => {
		if (nval.length > 0) {
			setRegionCode()
		}
	})
	
	// 表单
	const formRef = ref(null)
	const form = ref({
		name: '',
		company: '',
		province: '',
		addr: '',
		businessLicenseImg: '',
		storeImg: '',
		storeFaceImg: ''
	})
	// 表单验证
	const rules = ref({
		name: {
			rules: [{
				required: true,
				errorMessage: '请输入真实姓名'
			}]
		},
		company: {
			rules: [{
				required: true,
				errorMessage: '请输入企业/门店'
			}]
		},
		province: {
			rules: [{
				required: true,
				errorMessage: '请选择城市'
			}]
		},
		addr: {
			rules: [{
				required: true,
				errorMessage: '请输入详细地址'
			}]
		},
		businessLicenseImg: {
			rules: [{
				required: true,
				errorMessage: '请上传营业执照'
			}]
		},
		storeImg: {
			rules: [{
				required: true,
				errorMessage: '请上传门店照片'
			}]
		},
		storeFaceImg: {
			rules: [{
				required: true,
				errorMessage: '请上传门店环境'
			}]
		},
	})
	
	// 选择区域
	const regionCode = ref(userStore.regionCode || '')
	const onChangeAddr = (e) => {
		form.value.regionCode = e.detail.value?.[0].value
		form.value.province = e.detail.value.reduce((prev, cur, index, arr) => {
			return prev + cur.text
		}, '')
	}
	
	// 图片显示
	const imgUrlList = (data, key) => {
		return data[key] && data[key].indexOf('noimg.png') === -1 ? [{
			status: 'success',
			message: '上传成功',
			url: data[key],
			type: 'image'
		}] : []
	}
	
	// 图片上传
	const fileList = ref({
		businessLicenseImg: [],
		storeImg: [],
		storeFaceImg: []
	})
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value[`${event.name}`].splice(event.index, 1)
		form.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value[`${event.name}`].length
	  lists.map((item) => {
	    fileList.value[`${event.name}`].push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[`${event.name}`][fileListLen]
	    fileList.value[`${event.name}`].splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		form.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	};
	
	// 表单提交
	const isSubmit = ref(false)
	const submit = () => {
		formRef.value.validate().then(formRes => {
			isSubmit.value = true
			const params = {
				...form.value
			}
			perfectEdit(params).then(res => {
				uni.$u.toast(res.msg)
				isSubmit.value = false
				uni.$u.sleep(1000).then(async () => {
					if (type.value == 1) {
						await userStore.getUserInfo()
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						uni.navigateBack({
							delta: 1
						})
					}
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	
	onReady(() => {
		formRef.value.setRules(rules.value)
	})
	
</script>

<style lang="scss">
	.perfect {
		padding: 20rpx;
	}
	.form {
		padding: 0rpx 32rpx;
		border-radius: 20rpx;
		background-color: #ffffff;
		&-text {
			min-height: $input-height;
			font-size: 28rpx;
			color: $text-dark;
			&-img {
				width: 80px;
				height: 80px;
			}
		}
		&-checked {
			height: $input-height;
			justify-content: flex-end;
		}
		&-submit {
			height: $button-height;
			padding: 0;
			margin: 0;
			margin-top: 40rpx;
			font-size: 32rpx;
		}
	}
	:deep(.uni-data-tree) {
		width: calc(646rpx - 86px);
		height: $input-height;
		.uni-data-tree-input {
			height: 100%;
			.input-value {
				height: 100%;
			}
		}
	}
</style>
